import java.util.Arrays;
import java.util.Scanner;

public class test {
    static char[][] arr = new char[6][6];
    static char[][] copy = new char[6][6];
    static int[] xh = {-1,0,1,0,0};
    static int[] yh = {0,0,0,-1,1};
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        int n  = s.nextInt();
        while(n-- >0) {
            for(int i=0;i<5;i++) arr[i] = s.next().toCharArray();

            int min =10;
                for(int k=0; k<32; k++) {
                    int count = 0;
                    //数组拷贝
                    for(int i=0;i<5;i++)  copy[i] = Arrays.copyOf(arr[i],5);

                    //看不懂？
                        for(int i=0;i<5;i++)
                           if((k>>i&1) == 1) {
                               count++;
                               turn(0,i);
                           }

                       for(int i=0;i<4;i++)
                           for (int j = 0; j < 5; j++) {
                               if(arr[i][j] == '0') {
                                   count++;
                                   turn(i+1,j);
                               }
                           }

                       boolean dark = true;
                       for(int i=0;i<5;i++)
                           if(arr[4][i] == '0') {
                               dark = false;
                               break;
                           }

                       if(dark) min = Math.min(min,count);
                    for(int i=0;i<5;i++)  arr[i] = Arrays.copyOf(copy[i],5);
                }
                if(min>6) System.out.println(-1);
                else System.out.println(min);
        }
    }
    private static void turn(int x, int y) {
        for(int i=0; i<5; i++) {
            int a = x+xh[i];
            int b= y+yh[i];
            if(a>=0 && a<5 && b>=0 && b<5) arr[a][b]^=1;
        }
    }
}